using AdminAuthority;

using Abc.Core;
using Abc.Core.Entities;

using Furion.DatabaseAccessor;
using Furion.DependencyInjection;

using Mapster;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Tool;

namespace Abc.Application
{
    /// <summary>
    /// 功能/Action
    /// </summary>
    [ApiDescriptionSettings(Name = "Permission")]
    //[Injection(Proxy = typeof(LogDispatchProxy))]
    [ServiceFilter(typeof(ApiActionFilterAttribute))]
    public class PermissionService : IPermissionService, ITransient
    {
        private readonly ILogger<PermissionService> _logger;
        private readonly IRepository<Permission> _permissionRepository;

        //private readonly IMemoryCache _memoryCache;
        private readonly ICacheService _cacheService;

        public PermissionService(ILogger<PermissionService> logger
        //, IMemoryCache memoryCache
        , IRepository<Permission> permissionRepository
        , ICacheService cacheService)
        {
            _logger = logger;
            // _memoryCache = memoryCache;
            //_memoryCache =  App.GetService<IMemoryCache>();
            _permissionRepository = permissionRepository;
            _cacheService = cacheService;
        }

        /// <summary>
        /// 新增或更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> InsertOrUpdate(PermissionInput input)
        {
            var resultdata = new ResultData<string>();
            if (input.Id > 0)
            {
                var dbentity = await _permissionRepository.FindAsync(input.Id);
                input.Adapt(dbentity);
                await _permissionRepository.UpdateAsync(dbentity);
            }
            else
            {
                var newEntity = await _permissionRepository.InsertAsync(input.Adapt<Permission>());
            }
            resultdata.Succeeded = true;
            resultdata.Errors = "成功";
            return resultdata;
        }

        /// <summary>
        /// 删除一条
        /// </summary>
        /// <param name="id"></param>
        public async Task<ResultData<string>> Delete(int id)
        {
            var resultdata = new ResultData<string>();
            await _permissionRepository.DeleteAsync(id);

            resultdata.Succeeded = true;
            resultdata.Errors = "成功";
            return resultdata;
        }

        /// <summary>
        /// 查询一条[跟踪实体]
        /// </summary>
        /// <param name="id"></param>
        public async Task<PermissionOut> Find(int id)
        {
            var dbentity = await _permissionRepository.FindAsync(id);
            return dbentity.Adapt<PermissionOut>();
        }

        /// <summary>
        /// 查询一条[跟踪实体]
        /// </summary>
        /// <param name="id"></param>
        public async Task<PermissionOut> Get(int id)
        {
            var dbentity = await _permissionRepository.FirstOrDefaultAsync(o => o.Id == id, tracking: false);
            if (dbentity == null) return null;
            return dbentity.Adapt<PermissionOut>();
        }

        ///// <summary>
        ///// 分页查询
        ///// </summary>
        ///// <param name="searchQuery"></param>
        ///// <returns></returns>
        //public async Task<PagedListToLayui<PermissionDto>> GetAllByPageToLayui(PermissionQuery searchQuery)
        //{
        //    //var queryable= _permissionRepository.DetachedEntities.AsQueryable();
        //    //if (!string.IsNullOrWhiteSpace(searchQuery.KeyWords))
        //    //{
        //    //    var kw = searchQuery.KeyWords.ToLower();
        //    //    queryable = queryable.Where(o => o.No.Contains(kw));
        //    //}

        //    var entities =await _cacheService.GetPermissionEntities();

        //    return entities.Adapt<List<PermissionDto>>();
        //    //var pageResult = _permissionRepository.DetachedEntities.AsQueryable().OrderByDescending(o => o.Id).ProjectToType<PermissionDto>();
        //    //return await pageResult.ToPagedListToLayuiAsync(searchQuery.Page, searchQuery.Limit);
        //}
        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<PermissionOut>> GetAll()
        {
            var entities = await _cacheService.GetPermissionEntities();
            //var datas = await entities.ToListAsync();
            entities.SetMemoryCache("Table_Permission");
            return entities.Adapt<List<PermissionOut>>();
        }

        /// <summary>
        /// 更新权限
        /// </summary>
        /// <returns></returns>
        public async Task<ResultData<string>> UpdatePermission()
        {
            var resultdata = new ResultData<string>();

            var dbPermissions = await _permissionRepository.Entities.Where(o => o.IsAutoGeneration).ToListAsync();
            var mvcPermissions = AuthorityHelper.GetMvcPermissions();
            var apiPermissions = AuthorityHelper.GetApiPermissions();

            //移除后台 已经删除的权限
            foreach (var dbpermissionid in dbPermissions.Where(o => o.TypeCode.ToLower() == "admin").Select(o => o.Id).ToList())
            {
                var dbpermission = dbPermissions.First(o => o.Id == dbpermissionid);

                var mvcPermission = mvcPermissions.FirstOrDefault(o => o.Controller.ToLower().Trim() == dbpermission.Controller.ToLower().Trim() && o.Actions.ToLower().Trim() == dbpermission.Actions.ToLower().Trim());
                if (mvcPermission == null)
                {
                    //最新权限中已不存在
                    dbPermissions.Remove(dbpermission);
                }
            }
            //移除API 已经删除的权限
            foreach (var dbpermissionid in dbPermissions.Where(o => o.TypeCode.ToLower() == "api").Select(o => o.Id).ToList())
            {
                var dbpermission = dbPermissions.First(o => o.Id == dbpermissionid);

                var apiPermission = apiPermissions.FirstOrDefault(o => o.Controller.ToLower().Trim() == dbpermission.Controller.ToLower().Trim() && o.Actions.ToLower().Trim() == dbpermission.Actions.ToLower().Trim());
                if (apiPermission == null)
                {
                    //最新权限中已不存在
                    dbPermissions.Remove(dbpermission);
                }
            }
            var addPermissions = new List<Permission>();
            foreach (var mvcPermission in mvcPermissions)
            {
                var dbpermission = dbPermissions.FirstOrDefault(o => o.Controller.ToLower().Trim() == mvcPermission.Controller.ToLower().Trim() && o.Actions.ToLower().Trim() == mvcPermission.Actions.ToLower().Trim());
                if (dbpermission == null)
                {
                    var addPermission = mvcPermission.Adapt<Permission>();
                    addPermission.TypeCode = "Admin";
                    addPermission.IsAutoGeneration = true;
                    addPermissions.Add(addPermission);
                }
                else
                {
                    mvcPermission.Adapt(dbpermission);
                }
            }

            foreach (var apiPermission in apiPermissions)
            {
                var dbpermission = dbPermissions.FirstOrDefault(o => o.Controller.ToLower().Trim() == apiPermission.Controller.ToLower().Trim() && o.Actions.ToLower().Trim() == apiPermission.Actions.ToLower().Trim());
                if (dbpermission == null)
                {
                    var addPermission = apiPermission.Adapt<Permission>();
                    addPermission.TypeCode = "API";
                    addPermission.IsAutoGeneration = true;
                    addPermissions.Add(addPermission);
                }
                else
                {
                    apiPermission.Adapt(dbpermission);
                }
            }

            await _permissionRepository.InsertAsync(addPermissions);
            return resultdata;
        }

        #region 默认未启用

        ///// <summary>
        ///// 新增一条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //public async Task<ResultData<string>> Insert(PermissionInput input)
        //{
        //    var resultdata = new ResultData<string>();
        //    var newEntity = await _permissionRepository.InsertAsync(input.Adapt<Permission>());
        //
        //    resultdata.Succeeded = true;
        //    resultdata.Errors = "成功";
        //    return resultdata;
        //}
        //
        ///// <summary>
        ///// 更新一条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //public async Task<ResultData<string>> Update(int id,PermissionInput input)
        //{
        //    var resultdata=new ResultData<string>();
        //    var dbentity = await _permissionRepository.FindAsync(id);
        //    input.Adapt(dbentity);
        //    await _permissionRepository.UpdateAsync(dbentity);
        //
        //    resultdata.Succeeded = true;
        //    resultdata.Errors = "成功";
        //    return resultdata;
        //}
        //
        ///// <summary>
        ///// 新增或更新多条
        ///// </summary>
        ///// <param name="inputs"></param>
        ///// <returns></returns>
        //public async Task<ResultData<string>> Inserts(List<PermissionInput> inputs)
        //{
        //    var resultdata = new ResultData<string>();
        //    var dbaddinputs = inputs.Adapt<List<Permission>>();
        //    await _permissionRepository.InsertAsync(dbaddinputs);
        //    resultdata.Succeeded = true;
        //    resultdata.Errors = "成功";
        //    return resultdata;
        //}
        ///// <summary>
        ///// 新增或更新多条
        ///// </summary>
        ///// <param name="inputs"></param>
        ///// <returns></returns>
        //public async Task<ResultData<string>> Updates(List<PermissionInput> inputs)
        //{
        //    var resultdata = new ResultData<string>();
        //    var ids = inputs.Select(o => o.Id).ToList();
        //    var dbentitys = await _permissionRepository.Where(u => ids.Any(a => a == u.Id)).ToListAsync();
        //    inputs.Adapt(dbentitys);
        //    await _permissionRepository.UpdateAsync(dbentitys);
        //
        //    resultdata.Succeeded = true;
        //    resultdata.Errors = "成功";
        //    return resultdata;
        //}
        //
        ///// <summary>
        ///// 新增或更新多条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //public async Task<ResultData<string>> InsertOrUpdates(List<PermissionInput> inputs)
        //{
        //    var resultdata = new ResultData<string>();
        //    if (inputs.Any(o => o.Id > 0))
        //    {
        //        var updates = inputs.Where(o => o.Id > 0);
        //        var ids = updates.Select(o=>o.Id).ToList();
        //        var dbentity =  _permissionRepository.Where(o=> ids.Any(a=>a==o.Id));
        //        inputs.Adapt(dbentity);
        //        await  _permissionRepository.UpdateAsync(dbentity);
        //    }
        //    else
        //    {
        //       var adds = inputs.Where(o => o.Id <= 0);
        //       await _permissionRepository.InsertAsync(adds.Adapt<List<Permission>>());
        //
        //    }
        //    resultdata.Succeeded = true;
        //    resultdata.Errors = "成功";
        //    return resultdata;
        //}
        //
        //

        ///// <summary>
        ///// 分页查询
        ///// </summary>
        ///// <param name="searchQuery"></param>
        ///// <returns></returns>
        //public async Task<PagedList<PermissionDto>> GetAllByPage(PermissionQuery searchQuery)
        //{
        //    //var queryable= _permissionRepository.DetachedEntities.AsQueryable(tracking:false);
        //    //if (!string.IsNullOrWhiteSpace(searchQuery.KeyWords))
        //    //{
        //    //    var kw = searchQuery.KeyWords.ToLower();
        //    //    queryable = queryable.Where(o => o.No.Contains(kw));
        //    //}
        //    var pageResult = _permissionRepository.DetachedEntities.AsQueryable().OrderByDescending(o => o.Id).ProjectToType<PermissionDto>();
        //
        //    return await pageResult.ToPagedListAsync(searchQuery.Page, searchQuery.Limit);
        //}
        //
        //
        //
        //
        ///// <summary>
        ///// 设置状态
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="state"></param>
        ///// <param name="field">字段名</param>
        ///// <returns></returns>
        //public async Task<ResultData<string>> SetState(int id, bool state, string field)
        //{
        //    var resultdata = new ResultData<string>();
        //    var entity = await _permissionRepository.FirstOrDefaultAsync(o => o.Id == id);
        //
        //    switch (field.ToLower())
        //    {
        //
        //
        //
        //
        //
        //
        //
        //
        //        case  "issystem" :
        //            {
        //                entity.IsSystem = state;
        //            }
        //            break;
        //
        //
        //        case  "isdisuse" :
        //            {
        //                entity.IsDisuse = state;
        //            }
        //            break;
        //
        //
        //        case  "isautogeneration" :
        //            {
        //                entity.IsAutoGeneration = state;
        //            }
        //            break;
        //
        //
        //
        //
        //        default:
        //            break;
        //    }
        //
        //    resultdata.Succeeded = true;
        //    resultdata.Errors = "成功";
        //    return resultdata;
        //}

        #endregion 默认未启用
    }

    public interface IPermissionService
    {
        /// <summary>
        /// 新增或更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        Task<ResultData<string>> InsertOrUpdate(PermissionInput input);

        /// <summary>
        /// 删除一条
        /// </summary>
        /// <param name="id"></param>
        Task<ResultData<string>> Delete(int id);

        /// <summary>
        /// 查询一条
        /// </summary>
        /// <param name="id"></param>
        Task<PermissionOut> Find(int id);

        /// <summary>
        /// 查询一条
        /// </summary>
        /// <param name="id"></param>
        Task<PermissionOut> Get(int id);

        ///// <summary>
        ///// 分页查询
        ///// </summary>
        ///// <param name="searchQuery"></param>
        ///// <returns></returns>
        //Task<PagedListToLayui<PermissionDto>> GetAllByPageToLayui(PermissionQuery searchQuery);

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        Task<List<PermissionOut>> GetAll();

        /// <summary>
        /// 更新权限
        /// </summary>
        /// <returns></returns>
        Task<ResultData<string>> UpdatePermission();

        #region 默认未启用

        ///// <summary>
        ///// 新增一条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> Insert(PermissionInput input);
        //
        ///// <summary>
        ///// 更新一条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> Update(int id,PermissionInput input);
        ///// <summary>
        ///// 新增或更新一条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> Inserts(List<PermissionInput> inputs);
        ///// <summary>
        ///// 新增或更新多条
        ///// </summary>
        ///// <param name="inputs"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> Updates(List<PermissionInput> inputs);
        ///// <summary>
        ///// 新增或更新多条
        ///// </summary>
        ///// <param name="inputs"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> InsertOrUpdates(List<PermissionInput> inputs);

        ///// <summary>
        ///// 分页查询
        ///// </summary>
        ///// <param name="searchQuery"></param>
        ///// <returns></returns>
        //Task<PagedList<PermissionDto>> GetAllByPage(PermissionQuery searchQuery);
        ///// <summary>
        ///// 设置状态
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="state"></param>
        ///// <param name="field">字段名</param>
        ///// <returns></returns>
        //Task<ResultData<string>> SetState(int id, bool state, string field);

        #endregion 默认未启用
    }
}